package threading;

//线程不安全
/*
class Counter{
    private int count=0;
    synchronized public void add(){
            count++;
    }
    */
/*public void add(){与上面的写法一致
        synchronized (this){
            count++;
        }+
    }*//*

    public int get(){
        return count;
    }
}
//两个线程针对同一个变量自增50000次
public class ThreadDEmo11 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t1 = new Thread(()->{
            for(int i=0;i<50000;i++){
                counter.add();
            }
        });
        Thread t2 = new Thread(()->{
            for(int i=0;i<50000;i++){
                counter.add();
            }
        });
        t1.start();
        t2.start();

        //等待两个线程执行结束，然后看结果
        t1.join();
        t2.join();

        System.out.println(counter.get());
    }
}
*/
class Counter{
    private int count=100000;
    synchronized public void add(){
        count++;
    }
    /*public void add(){与上面的写法一致
        synchronized (this){
            count++;
        }+
    }*/
    public void sub(){
        count--;
    }
    public int get(){
        return count;
    }
}
//两个线程针对同一个变量自增50000次
public class ThreadDEmo11 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t1 = new Thread(()->{
            for(int i=0;i<50000;i++){
                counter.sub();
            }
        });
        Thread t2 = new Thread(()->{
            for(int i=0;i<50000;i++){
                counter.sub();
            }
        });
        t1.start();
        t2.start();

        //等待两个线程执行结束，然后看结果
        t1.join();
        t2.join();

        System.out.println(counter.get());
    }
}
